#    This file is part of robo-ircbot.
#
#    robo-ircbot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    robo-ircbot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with robo-ircbot.  If not, see <http://www.gnu.org/licenses/>.

package App::Modular::Module::Correction;
use strict;
use warnings;
use base qw(App::Modular::Module);

print ":: Correction module loaded.\n";

# Holds the last thing said.
my %last_said = ();

# Events we want to receive.
sub events { return "PRIVMSG"; }

sub help {
        return (
                "Correct the previous line of text.",
                "s/<regexp>/<replace>/[g] [&& ...]"
        );
}

# PRIVMSG events.
sub event_privmsg
{
        shift;
        my $e = shift;

        my $help = $e->robo->mod("Helper") || return;

        # Admin commands for slashdot module.
        if ($help->trigger_switch("correction", $e)) {
                record_said($e, $help);
                return;
        }

        my @data = split(/\s*\&\&\s*/, $e->data);
        my $did_something = 0;
        my $last = $last_said{$e->dest."_DATA"} || "";
        my $ts = $last_said{$e->dest."_TIMESTAMP"} || "";

        foreach (@data) {
                # Search and replace trigger.
                if ($_ =~ /^s\/(.+)\/(g)?$/) {
                        eval("\$last =~ s/".$1."/g") if ($2);
                        eval("\$last =~ s/".$1."/") unless ($2);

                        # Remove \r\n to prevent expoits.
                        $last =~ s/[\r\n]//g;

                        if (!$@) {
                                $did_something = 1;
                        }
                }
        }

        $e->s("PRIVMSG ".$e->dest." :".$ts.$last) if ($did_something);
        record_said($e, $help) unless ($did_something);
}

# Store the last thing said for a specific channel/private message.
sub record_said
{
        my ($e, $help) = @_;

        my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
        my $nick = $help->parse_nick($e->from);

        if ($hour < 10) { $hour = "0".$hour; }
        if ($min < 10) { $min = "0".$min; }

        # Store line as last said.
        if ($e->data =~ /^\001ACTION (.+)\001/) {
                $last_said{$e->dest."_DATA"} = $1;
                $last_said{$e->dest."_TIMESTAMP"} = $hour.":".$min." \002* ".$nick."\002 ";
        } else {
                $last_said{$e->dest."_DATA"} = $e->data;
                $last_said{$e->dest."_TIMESTAMP"} = $hour.":".$min." <".$nick."> ";
        }
}

1;
